<?php

namespace App\Http\Controllers;

use App\Models\Business\Business as BusinessModel;
use App\Models\Product\Product as ProductModel;
use App\Models\Product\Cart as CartModel;
use App\Models\Business\Record as RecordModel;
use App\Models\Product\Order as OrderModel;
use App\Models\Product\Orderproduct as OrderproductModel;
use App\Models\Business\Address as AddressModel;
use App\Models\Depot\Back as DepotModel;
use App\Models\Depot\BackProduct as BackProductModel;
use App\Models\Expressquery as ExpressqueryModel;
use App\Models\Config as ConfigModel;

use Illuminate\Http\Request;
// 引入Validator 
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;



class Order extends Controller
{
  // 下单
  public function add(\Exception $e)
  {
    $amount = request('amount', 0);
    $busid = request('busid', 0);
    $businessaddrid = request('businessaddrid', 0);
    $cartids = request('cartids', 0);
    $remark = request('remark', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $addressinfo = AddressModel::find($businessaddrid);
    if (!$addressinfo) {
      return error('当前收货地址不存在');
    }

    // 判断用户余额
    $money = bcsub($userinfo['money'], $amount, 2);

    if ($money < 0) {
      return error("当前用户余额不足");
    }

    $cartids = explode(',', $cartids);

    // 查询购物车数据
    $cartinfo = CartModel::whereIn('id', $cartids)->get();

    if (count($cartinfo) < count($cartids)) {
      return error("当前购物车商品不存在");
    }

    // 商品数据
    $productlist = [];

    // 判断商品库存
    foreach ($cartinfo as $item) {
      $res = ProductModel::find($item['proid']);
      if (!$res) {
        return error("当前商品不存在");
      }

      $stock = bcsub($res['stock'], $item['nums']);
      if ($stock < 0) {
        return error("当前{$res['name']}库存不足");
      }

      $productlist[] = [
        'id' => $res['id'],
        'stock' => $stock
      ];
    }
    /*
        开启事务  startTrans  rollback
        1、订单表  新增
        2、订单产品表  新增
        3、购物车  删除
        4、用户表  更新
        5、产品表库存 更新
        6、消费记录表  新增
    */
    DB::beginTransaction();

    try {

      // 订单号
      $code = build_code('SP');

      $orderdata = [
        'code' => $code,
        'busid' => $busid,
        'businessaddrid' => $businessaddrid,
        'amount' => $amount,
        'remark' => $remark,
        'status' => '1'
      ];

      // 验证规则
      $orderrules = [
        'code' => 'required',
        'busid' => 'required',
        'businessaddrid' => 'required',
        'amount' => 'required',
        'status' => 'required'
      ];

      // 错误提示信息
      $ordermessage = [
        'code.required' => '订单号必须填写',
        'busid.required' => '用户信息必须填写',
        'businessaddrid.required'   => '收货地址必须填写',
        'amount.required'  => '订单金额必须填写',
      ];

      $ordervalidator = Validator::make($orderdata, $orderrules, $ordermessage);

      if ($ordervalidator->fails()) {
        // errors 获取所有错误信息
        $errors = $ordervalidator->errors();
        // first 第一个错误信息;
        return error($errors->first());
      }

      // 订单表  新增  使用 insertGetId 方法来插入记录可以返回 ID 值
      $orderStutas = OrderModel::create($orderdata);

      if ($orderStutas === false) {
        return error($e->getMessage());
      }

      $orderproduct = [];

      foreach ($cartinfo as $item) {
        // 组装订单产品表的数据 
        $orderproduct[] = [
          'orderid' =>  $orderStutas->id,
          'proid' => $item['proid'],
          'pronum' => $item['nums'],
          'price' => $item['price'],
          'total' => $item['total']
        ];
      }

      // 验证规则
      $orderprodrules = [
        'orderid' => 'required',
        'proid' => 'required',
        'pronum' => 'required',
        'price' => 'required',
        'total' => 'required'
      ];

      // 错误提示信息
      $orderprodmessage = [
        'orderid.required' => '订单ID必须填写',
        'proid.required' => '商品ID必须填写',
        'pronum.required'   => '商品数量必须填写',
        'price.required'  => '商品单价必须填写',
        'total.required'  => '商品总价必须填写',
      ];

      foreach ($orderproduct as $value) {
        $orderprodvalidator = Validator::make($value, $orderprodrules, $orderprodmessage);
        if ($orderprodvalidator->fails()) {
          // errors 获取所有错误信息
          $errors = $orderprodvalidator->errors();
          // first 第一个错误信息;
          return error($errors->first());
        }
      }

      // 订单产品表  新增
      $orderproductStutas = OrderproductModel::insert($orderproduct);

      if ($orderproductStutas === false) {
        return error($e->getMessage());
      }

      // 购物车  删除
      $cartStutas = CartModel::destroy($cartids);

      if ($cartStutas === false) {
        return error($e->getMessage());
      }

      // 用户表  更新
      $businessStutas = BusinessModel::where(['id' => $busid])->update(['money' => $money]);
      if ($businessStutas === false) {
        return error($e->getMessage());
      }

      // 产品表库存 更新
      $productStutas = $this->updateBatch('pre_product', $productlist);

      if ($productStutas === false) {
        return error($e->getMessage());
      }

      $recorddata = [
        'total' => $amount,
        'content' => "商城订单号：" . $code . "---消费的金额：" . $amount . " 元",
        'busid' => $busid,
        'state' => '2'
      ];

      // 验证规则
      $recordrules = [
        'total' => 'required',
        'busid' => 'required',
        'content' => 'required',
        'state' => 'required',
      ];

      // 错误提示信息
      $recordmessage = [
        'total.required'  => '消费金额必须填写',
        'busid.required' => '用户信息必须填写',
        'content.required' => '消费描述必须填写',
        'state.required'   => '消费状态必须填写'
      ];

      $recordvalidator = Validator::make($recorddata, $recordrules, $recordmessage);

      if ($recordvalidator->fails()) {
        // errors 获取所有错误信息
        $errors = $recordvalidator->errors();
        // first 第一个错误信息;
        return error($errors->first());
      }

      // 消费记录表  新增
      $recordStutas = RecordModel::create($recorddata);
      if ($recordStutas === false) {
        return error($e->getMessage());
      }
      DB::commit();
      return success('下单成功');
    } catch (QueryException | \Exception $ex) {
      DB::rollback();
      return error($ex->getMessage());
      return error('下单失败');
    }
  }

  // 立即购买
  public function buynow()
  {
    $amount = request('amount', 0);
    $busid = request('busid', 0);
    $businessaddrid = request('businessaddrid', 0);
    $proid = request('proid', 0);
    $remark = request('remark', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $addressinfo = AddressModel::find($businessaddrid);
    if (!$addressinfo) {
      return error('当前收货地址不存在');
    }

    // 判断用户余额
    $money = bcsub($userinfo['money'], $amount, 2);

    if ($money < 0) {
      return error("当前用户余额不足");
    }

    $productinfo = ProductModel::find($proid);
    if (!$productinfo) {
      return error("当前商品不存在");
    }

    $stock = bcsub($productinfo['stock'], 1);
    if ($stock < 0) {
      return error("当前{$productinfo['name']}库存不足");
    }

    /*
        开启事务  startTrans  rollback
        1、订单表  新增
        2、订单产品表  新增
        3、用户表  更新
        4、产品表库存 更新
        5、消费记录表  新增
    */
    DB::beginTransaction();

    try {
      // 订单号
      $code = build_code('SP');

      $orderdata = [
        'code' => $code,
        'busid' => $busid,
        'businessaddrid' => $businessaddrid,
        'amount' => $amount,
        'remark' => $remark,
        'status' => '1'
      ];

      // 验证规则
      $orderrules = [
        'code' => 'required',
        'busid' => 'required',
        'businessaddrid' => 'required',
        'amount' => 'required',
        'status' => 'required'
      ];

      // 错误提示信息
      $ordermessage = [
        'code.required' => '订单号必须填写',
        'busid.required' => '用户信息必须填写',
        'businessaddrid.required'   => '收货地址必须填写',
        'amount.required'  => '订单金额必须填写',
      ];

      $ordervalidator = Validator::make($orderdata, $orderrules, $ordermessage);

      if ($ordervalidator->fails()) {
        // errors 获取所有错误信息
        $errors = $ordervalidator->errors();
        // first 第一个错误信息;
        return error($errors->first());
      }

      // 订单表  新增  使用 insertGetId 方法来插入记录可以返回 ID 值
      $orderStutas = OrderModel::create($orderdata);

      if ($orderStutas === false) {
        return error('订单创建失败');
      }

      // 组装订单产品表的数据
      $orderproduct = [
        'orderid' =>  $orderStutas->id,
        'proid' => $proid,
        'pronum' => 1,
        'price' => $amount,
        'total' => $amount
      ];

      // 验证规则
      $orderprodrules = [
        'orderid' => 'required',
        'proid' => 'required',
        'pronum' => 'required',
        'price' => 'required',
        'total' => 'required'
      ];

      // 错误提示信息
      $orderprodmessage = [
        'orderid.required' => '订单ID必须填写',
        'proid.required' => '商品ID必须填写',
        'pronum.required'   => '商品数量必须填写',
        'price.required'  => '商品单价必须填写',
        'total.required'  => '商品总价必须填写',
      ];

      $orderprodvalidator = Validator::make($orderproduct, $orderprodrules, $orderprodmessage);
      if ($orderprodvalidator->fails()) {
        // errors 获取所有错误信息
        $errors = $orderprodvalidator->errors();
        // first 第一个错误信息;
        return error($errors->first());
      }

      // 订单产品表  新增
      $orderproductStutas = OrderproductModel::insert($orderproduct);

      if ($orderproductStutas === false) {
        return error('订单商品生成失败');
      }

      // 用户表  更新
      $businessStutas = BusinessModel::where(['id' => $busid])->update(['money' => $money]);

      // if ($businessStutas === false) {
      //   return error($e->getMessage());
      // }

      // 产品表库存 更新
      $productStutas = ProductModel::where(['id' => $proid])->update(['stock' => $stock]);;
      // if ($productStutas === false) {
      //   return error($e->getMessage());
      // }

      $recorddata = [
        'total' => $amount,
        'content' => "商城订单号：" . $code . "---消费的金额：" . $amount . " 元",
        'busid' => $busid,
        'state' => '2'
      ];

      // 验证规则
      $recordrules = [
        'total' => 'required',
        'busid' => 'required',
        'content' => 'required',
        'state' => 'required',
      ];

      // 错误提示信息
      $recordmessage = [
        'total.required'  => '消费金额必须填写',
        'busid.required' => '用户信息必须填写',
        'content.required' => '消费描述必须填写',
        'state.required'   => '消费状态必须填写'
      ];

      $recordvalidator = Validator::make($recorddata, $recordrules, $recordmessage);

      if ($recordvalidator->fails()) {
        // errors 获取所有错误信息
        $errors = $recordvalidator->errors();
        // first 第一个错误信息;
        return error($errors->first());
      }

      // 消费记录表  新增
      $recordStutas = RecordModel::create($recorddata);
      // if ($recordStutas === false) {
      //   return error($e->getMessage());
      // }
      DB::commit();
      return success('下单成功');
    } catch (QueryException | \Exception $ex) {
      DB::rollback();
      return error($ex->getMessage());
      return error('下单失败');
    }
  }

  // 订单列表
  public function index()
  {

    $busid = request('busid', 0);
    $status = request('status', '');

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $qb = OrderModel::query();

    // 判断订单状态不为空
    if (!empty($status) || $status == '0') {
      // 前端显示售后中 代表查询状态为：-1,-2,-3 
      if ($status == '-1') {
        $status = ['-1', '-2', '-3'];
      }
      // 前端显示售后已结束，代表查询状态为: -4, -5
      else if ($status == '-4') {
        $status = ['-4', '-5'];
      } else {
        $status = [$status];
      }
    }


    $orderlist = $qb->whereIn('status', $status)->where('busid', $busid)->orderBy('createtime', 'desc')->get();

    foreach ($orderlist as $item) {
      $product = OrderproductModel::with('product')->where('orderid', $item['id'])->first();
      $item['info'] = $product;
    }

    return success('', '', $orderlist);
  }

  // 订单详情
  public function info()
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::with(['express', 'address'])->find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $product = OrderproductModel::with('product')->where('orderid', $orderinfo['id'])->get();

    $orderinfo['info'] = $product;

    // 厂家地址信息
    $contact = ConfigModel::where('name', 'contact')->value('value');
    $mobile = ConfigModel::where('name', 'mobile')->value('value');
    $address = ConfigModel::where('name', 'address')->value('value');

    $orderinfo['factory'] = [
      'contact' => $contact,
      'mobile' => $mobile,
      'address' => $address,
    ];

    return success('', '', $orderinfo);
  }

  // 确认收货
  public function receipt()
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $data = [
      'status' => '3'
    ];

    $result = OrderModel::where(['id' => $orderid])->update($data);

    if ($result === false) {
      return error('确认收货失败');
    } else {
      return success('确认收货成功');
    }
  }

  // 申请退货
  public function retreat()
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);
    $status = request('status', '');
    $refundreason = request('refundreason', '');

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $data = [
      'status' => $status,
      'refundreason' => $refundreason
    ];
    $result = OrderModel::where(['id' => $orderid])->update($data);
    if ($result === false) {
      return error('申请退货失败');
    } else {
      return success('申请退货成功');
    }
  }

  // 订单商品退货
  public function refundgoods(\Exception $e)
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);
    $expressid = request('expressid', '');
    $expresscode = request('expresscode', '');
    $addressid = request('addressid', 0);


    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $addressinfo = AddressModel::find($addressid);

    if (!$addressinfo) {
      return error('当前寄件地址不存在');
    }

    $orderproductlist = OrderproductModel::where('orderid', $orderid)->get();

    if (!$orderproductlist) {
      return error('当前订单商品不存在');
    }

    $exxpressqueryinfo = ExpressqueryModel::find($expressid);

    if (!$exxpressqueryinfo) {
      return error('当前物流不存在');
    }

    DB::beginTransaction();

    try {

      $depotData = [
        'code' => build_code('BP'),
        'ordercode' => $orderinfo['code'],
        'busid' => $busid,
        'amount' => $orderinfo['amount'],
        'status' => '1',
        'expressid' => $expressid,
        'expresscode' => $expresscode,
        'contact' => $addressinfo['consignee'],
        'phone' => $addressinfo['mobile'],
        'address' => $addressinfo['address'],
        'province' => $addressinfo['province'],
        'city' => $addressinfo['city'],
        'district' => $addressinfo['district'],
      ];

      $depotStutas = DepotModel::create($depotData);
      if ($depotStutas === false) {
        return error($e->getMessage());
      }

      $productlist = [];

      // 组装退货商品数据
      foreach ($orderproductlist as $item) {

        $productlist[] = [
          'backid' => $depotStutas->id,
          'proid' => $item['proid'],
          'nums' => $item['pronum'],
          'price' => $item['price'],
          'total' => $item['total']
        ];
      }

      $backproductStutas = BackProductModel::insert($productlist);;
      if ($backproductStutas === false) {
        return error($e->getMessage());
      }

      DB::commit();
      return success('退货物流成功');
    } catch (QueryException $ex) {
      DB::rollback();
      return error('退货物流失败');
    }
  }

  // 退货详情
  public function refundinfo()
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $where = [];
    $where['ordercode'] = $orderinfo['code'];
    $where['busid'] = $busid;

    $DepotModelinfo = DepotModel::where($where)->first();

    if (!$DepotModelinfo) {
      return error('当退货单不存在');
    }

    $data = [
      'depotinfo' => $DepotModelinfo,
    ];

    if (!empty($DepotModelinfo['expresscode'])) {

      // 假数据测试
      // $lists = '[{"time":"2018-03-09 11:59:26","status":"【石家庄市】 快件已在 【长安三部】 签收,签收人: 本人, 感谢使用中通快递,期待再次为您服务!"},{"time":"2018-03-09 09:03:10","status":"【石家庄市】快件已到达【长安三部】（0311-85344265）,业务员 容晓光（15908220064）正在第1次派件"},{"time":"2018-03-08 23:43:44","status":"【石家庄市】 快件离开 【石家庄】 发往 【长安三部】"},{"time":"2018-03-08 21:00:44","status":"【石家庄市】 快件到达 【石家庄】"},{"time":"2018-03-07 01:38:45","status":"【广州市】 快件离开 【广州中心】 发往 【石家庄】"},{"time":"2018-03-07 01:36:53","status":"【广州市】 快件到达 【广州中心】"},{"time":"2018-03-07 00:40:57","status":"【广州市】 快件离开 【广州花都】 发往 【石家庄中转】"},{"time":"2018-03-07 00:01:55","status":"【广州市】 【广州花都】（020-37738523） 的 马溪 （18998345739） 已揽收"}]';

      // cache()->put($orderinfo['expresscode'], json_decode($lists, true));

      if (cache()->get($DepotModelinfo['expresscode'])) {
        $data['express'] = cache($DepotModelinfo['expresscode']);
        return success('', '', $data);
      } else {
        // 调用公共的物流信息方法
        $res = query_express($DepotModelinfo['expresscode']);

        if ($res['result']) {
          // 设置缓存数据
          cache()->put($DepotModelinfo['expresscode'], $res['data']);
          $data['express'] = $res['data'];
          return success('', '', $data);
        }
      }
    }

    $data['express'] = [];
    return success('', '', $data);
  }

  // 物流详情
  public function express()
  {
    $busid = request('busid', 0);
    $orderid = request('orderid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderinfo = OrderModel::with(['express', 'address'])->find($orderid);

    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $data = [
      'orderinfo' => $orderinfo,
    ];

    if (!empty($orderinfo['expresscode'])) {

      // 假数据测试
      // $lists = '[{"time":"2018-03-09 11:59:26","status":"【石家庄市】 快件已在 【长安三部】 签收,签收人: 本人, 感谢使用中通快递,期待再次为您服务!"},{"time":"2018-03-09 09:03:10","status":"【石家庄市】快件已到达【长安三部】（0311-85344265）,业务员 容晓光（15908220064）正在第1次派件"},{"time":"2018-03-08 23:43:44","status":"【石家庄市】 快件离开 【石家庄】 发往 【长安三部】"},{"time":"2018-03-08 21:00:44","status":"【石家庄市】 快件到达 【石家庄】"},{"time":"2018-03-07 01:38:45","status":"【广州市】 快件离开 【广州中心】 发往 【石家庄】"},{"time":"2018-03-07 01:36:53","status":"【广州市】 快件到达 【广州中心】"},{"time":"2018-03-07 00:40:57","status":"【广州市】 快件离开 【广州花都】 发往 【石家庄中转】"},{"time":"2018-03-07 00:01:55","status":"【广州市】 【广州花都】（020-37738523） 的 马溪 （18998345739） 已揽收"}]';

      // cache()->put($orderinfo['expresscode'], json_decode($lists, true));

      if (cache()->get($orderinfo['expresscode'])) {
        $data['express'] = cache($orderinfo['expresscode']);
        return success('', '', $data);
      } else {
        // 调用公共的物流信息方法
        $res = query_express($orderinfo['expresscode']);
        if ($res['result']) {
          // 设置缓存数据
          cache()->put($orderinfo['expresscode'], $res['data']);
          $data['express'] = $res['data'];
          return success('', '', $data);
        }
      }
    }
    $data['express'] = [];
    return success('', '', $data);
  }

  // 订单产品详情
  public function infoproduct()
  {
    $busid = request('busid', 0);
    $orderproid = request('orderproid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    $orderproduct = OrderproductModel::with('product')->find($orderproid);

    if (!$orderproduct) {
      return error('当前订单商品不存在');
    }

    $orderinfo = OrderModel::with(['express', 'address'])->find($orderproduct['orderid']);


    if (!$orderinfo) {
      return error('当前订单不存在');
    }

    $orderinfo['info'] = $orderproduct;

    return success('', '', $orderinfo);
  }

  // 商品评价
  public function rate(Request $request, \Exception $e)
  {
    $busid = request('busid', 0);
    $orderproid = request('orderproid', '');
    $rate = request('rate', 0);
    $comment = request('comment', '');

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      $this->error('当前用户不存在');
    }

    $orderinfo = OrderproductModel::find($orderproid);

    if (!$orderinfo) {
      $this->error('当前订单商品不存在');
    }

    // 判断当前订单商品是否全部评价
    $isShow = false;

    // 查询当前订单的所有订单商品
    $orderlist = OrderproductModel::where('orderid', $orderinfo['orderid'])->get();

    // 判断当前订单商品是否全部评价
    foreach ($orderlist as $item) {
      if (empty($item['rate'])) {
        if ($item['id'] != $orderproid) {
          $isShow = true;
        }
      }
    }

    // 订单商品有多个
    if ($isShow) {

      $data = [
        'rate' => $rate,
        'comment' => $comment,
        'busid' => $busid
      ];

      if (isset($_FILES[$orderproid]) &&  $_FILES[$orderproid]['size'] > 0 && array_count_values($_FILES[$orderproid]['error'])[0] == count($_FILES[$orderproid]['error'])) {

        $res = uploads($orderproid, $request);

        if ($res['code'] == 1) {
          $url = $res['msg'];
          $data['proimg'] = implode(',', $url);
        }
      }

      $result = OrderproductModel::where('id', $orderproid)->update($data);

      if ($result === false) {
        return error('评价失败');
      } else {
        return success('评价成功');
      }
    } else {

      DB::beginTransaction();
      try {

        $orderdata = [
          'status' => '4'
        ];

        // 订单表改状态
        $orderStutas = OrderModel::where('id', $orderinfo['orderid'])->update($orderdata);

        if ($orderStutas === false) {
          return error($e->getMessage());
        }

        $orderproductdata = [
          'rate' => $rate,
          'comment' => $comment,
          'busid' => $busid
        ];

        if (isset($_FILES[$orderproid]) &&  $_FILES[$orderproid]['size'] > 0 && array_count_values($_FILES[$orderproid]['error'])[0] == count($_FILES[$orderproid]['error'])) {

          $res = uploads($orderproid, $request);

          if ($res['code'] == 1) {
            $url = $res['msg'];
            $orderproductdata['proimg'] = implode(',', $url);
          }
        }

        $orderproductStutas = OrderproductModel::where('id', $orderproid)->update($orderproductdata);

        if ($orderproductStutas === false) {
          return error($e->getMessage());
        }

        DB::commit();
        return success('评价成功');
      } catch (QueryException $ex) {
        DB::rollback();
        return error('评价失败');
      }
    }
  }

  // 获取所有的物流公司
  public function expresslist()
  {
    $busid = request('busid', 0);

    $userinfo = BusinessModel::find($busid);

    if (!$userinfo) {
      return error('当前用户不存在');
    }

    // 物流公司列表
    $expresslist = ExpressqueryModel::select('name as text', 'id as value')->get();

    // 收货地址列表
    $address = AddressModel::where('busid', $busid)->get();

    // 组装收货地址数据
    $addresslist = [];

    // 有收货地址
    if (count($address) > 0) {
      foreach ($address as $item) {
        $addresslist[] = [
          'value' => $item['id'],
          'text' => $item['consignee'] . '-' . $item['mobile'] . '-' . $item['address_text']
        ];
      }
    }


    $data = [
      'expresslist' => $expresslist,
      'addresslist' => $addresslist,
    ];

    return success('', '',  $data);
  }

  // 批量更新多条数据方法
  public function updateBatch($tableName = "", $multipleData = array())
  {
    if ($tableName && !empty($multipleData)) {

      // column or fields to update  
      $updateColumn = array_keys($multipleData[0]);
      $referenceColumn = $updateColumn[0]; //e.g id  
      unset($updateColumn[0]);
      $whereIn = "";

      $q = "UPDATE " . $tableName . " SET ";
      foreach ($updateColumn as $uColumn) {
        $q .=  $uColumn . " = CASE ";

        foreach ($multipleData as $data) {
          $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
        }
        $q .= "ELSE " . $uColumn . " END, ";
      }
      foreach ($multipleData as $data) {
        $whereIn .= "'" . $data[$referenceColumn] . "', ";
      }
      $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" .  rtrim($whereIn, ', ') . ")";

      // Update    
      return DB::update(DB::raw($q));
    } else {
      return false;
    }
  }
}
